import java.util.ArrayList;
import java.util.List;

/**
 * 面试题 08.09. 括号
 * https://leetcode-cn.com/problems/bracket-lcci/
 */
public class Solutions_mianshi_08_09 {
    public static void main(String[] args) {
        int n = 3;  // output: {"((()))", "(()())", "(())()", "()(())", "()()()"}
        List<String> result = generateParenthesis(n);
        System.out.println(result);
    }

    private static List<String> res = null;
    public static List<String> generateParenthesis(int n) {
        res = new ArrayList<>();
        backtrack(new StringBuilder(), 0, 0, n);
        return res;
    }

    public static void backtrack(StringBuilder sb, int left, int right, int n) {
        if (left == n && right == n) {
            // 结束条件：n 对括号配对完成
            res.add(sb.toString());
            return;
        }
        // 左括号放置条件：左括号数 left 小于 n
        if (left < n) {
            // 添加字符
            sb.append('(');
            // 递归
            backtrack(sb, left + 1, right, n);
            // 回溯：移除最后添加的字符
            sb.deleteCharAt(sb.length() - 1);
        }
        // 右括号放置条件：右括号数 right 小于 n，并且小于 left，因为必须先放 left，再放 right
        if (right < n && right < left) {
            sb.append(')');
            backtrack(sb, left, right + 1, n);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
